import React, { Component } from 'react'
import Pubsub from 'pubsub-js'
import Item from './Item'

export default class index extends Component {
  state = {
    users: [],
    isFirst: true,
    isLoading: false,
    err: ''
  }

  componentDidMount() {
    console.log('List组件挂载完毕')

    this.token = Pubsub.subscribe('search', (_, stateObj) => {
      this.setState(stateObj)
    })
  }

  componentWillUnmount() {
    console.log('List组件即将卸载')

    Pubsub.unsubscribe(this.token)
  }

  render() {
    const { users, isFirst, isLoading, err } = this.state

    return (
      <div className="row g-3 p-3">
        {isFirst ? (
          <h2>欢迎使用，请输入关键字，点击搜索！</h2>
        ) : isLoading ? (
          <div>Loading...</div>
        ) : (
          err ||
          users.map(item => {
            return <Item key={item.id} user={item} />
          })
        )}
      </div>
    )
  }
}
